package com.example.mscluster.consumer;

import okhttp3.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author daigl
 * @create 2019-12-6 上午9:54
 **/
@Component
public class OkHttpUtils implements Interceptor{

    private static OkHttpClient okHttpClient;
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static final MediaType XML = MediaType.parse("application/xml; charset=utf-8");

    {
        okHttpClient = new OkHttpClient();
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(15000,TimeUnit.MILLISECONDS);
        builder.writeTimeout(15000,TimeUnit.MILLISECONDS);
        builder.connectTimeout(15000,TimeUnit.MILLISECONDS);
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response proceed = chain.proceed(request);
        Response rp = proceed.newBuilder().removeHeader("Prgma").removeHeader("Cache-Control").addHeader("Cache-Control","max-age-20").build();
        return rp;
    }

    /**
     * getClientInfo 请求
     * @param url       请求url地址
     * @return string
     * */
    public static String doGet(String url) {
        return doGet(url, null, null);
    }


    /**
     * getClientInfo 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @return string
     * */
    public static String doGet(String url, Map<String, Object> params) {
        return doGet(url, params, null);
    }

    /**
     * getClientInfo 请求
     * @param url       请求url地址
     * @param headers   请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     * */
    public static String doGet(String url, String[] headers) {
        return doGet(url, null, headers);
    }


    /**
     * getClientInfo 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @param headers   请求头字段 {k1, v1 k2, v2, ...}
     * @return string
     * */
    public static String doGet(String url, Map<String, Object> params, String[] headers) {
        StringBuilder sb = new StringBuilder(url);
        if (params != null && params.keySet().size() > 0) {
            boolean firstFlag = true;
            for (String key : params.keySet()) {
                if (firstFlag) {
                    sb.append("?").append(key).append("=").append(params.get(key));
                    firstFlag = false;
                } else {
                    sb.append("&").append(key).append("=").append(params.get(key));
                }
            }
        }

        Request.Builder builder = new Request.Builder();
        if (headers != null && headers.length > 0) {
            int m = 2;
            if (headers.length % m == 0) {
                for (int i = 0; i < headers.length; i = i + m) {
                    builder.addHeader(headers[i], headers[i + 1]);
                }
            } else {
            }

        }

        Request request = builder.url(sb.toString()).build();
        return execute(request);
    }

    /**
     * post 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @return string
     */
    public static String doPost(String url, Map<String, String> params) {
        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, null != params.get(key)?params.get(key):"");
            }
        }
        Request request = new Request.Builder().url(url).post(builder.build()).build();

        return execute(request);
    }
    /**
     * put 请求
     * @param url       请求url地址
     * @param params    请求参数 map
     * @return string
     */
    public static String doPut(String url,Map<String,String> params){
        FormBody.Builder builder = new FormBody.Builder();

        if (params != null && params.keySet().size() > 0) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }

        Request request = new Request.Builder()
                .url(url)
                .put(builder.build())
                .build();
        return execute(request);
    }

    /**
     * post 请求, 请求数据为 json 的字符串
     * @param url       请求url地址
     * @param json      请求数据, json 字符串
     * @return string
     */
    public static String doPostJson(String url, String json) {
        return executePost(url, json, JSON);
    }

    /**
     * post 请求, 请求数据为 xml 的字符串
     * @param url       请求url地址
     * @param xml       请求数据, xml 字符串
     * @return string
     */
    public static String doPostXml(String url, String xml) {
        return executePost(url, xml, XML);
    }

    /**
     * 统一认证中心请求用户数据
     * @param url
     * @param token
     * @return
     */
    public static String doGetWithHeaders(String url,String token){
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Authorization", "Bearer "+token)
                .build();
        return execute(request);
    }

    private static String executePost(String url, String data, MediaType contentType) {
        RequestBody requestBody = RequestBody.create(contentType, data);
        Request request = new Request.Builder().url(url).post(requestBody).build();

        return execute(request);
    }


    /**
     * post 请求, 请求数据为 xml 的字符串
     * @param url       请求url地址
     * @param xml       请求数据, xml 字符串
     * @return string
     */
    public static String doPostXml(String url, String xml, Map<String, String> headParams) {
        return executePost(url, xml, XML, headParams);
    }
    /**
     * POST请求，请求带有头标签
     * @param url 请求路径
     * @param data 请求body的报文
     * @param mediaType 请求方式
     * @param headParams 请求报文头参数
     * @return 返回结果
     */
    private static String executePost(String url, String data, MediaType mediaType, Map<String, String> headParams) {
        RequestBody requestBody = RequestBody.create(mediaType, data);
        Headers headers = Headers.of(headParams);
        Request request = new Request.Builder()
                .headers(headers)
                .url(url).post(requestBody).build();
        return execute(request);
    }

    /**
     * 执行okhttp请求
     * @param request
     * @return
     */
    private static String execute(Request request) {
        Response response = null;
        try {
            response = okHttpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                return response.body().string();
            }
        } catch (Exception e) {
        } finally {
            if (response != null) {
                response.close();
            }
        }
        return "";
    }

}
